package com.me.learnspring.service;

import com.me.learnspring.common.OrderState;
import com.me.learnspring.controller.request.NewOrderRequest;
import com.me.learnspring.model.Drink;
import com.me.learnspring.repository.DrinkRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Optional;
import java.util.List;
import com.me.learnspring.repository.OrderRepository;
import com.me.learnspring.model.Order;

import javax.transaction.Transactional;

@Slf4j
@Service
public class OrderService {
	@Autowired
	private OrderRepository oRepository;
	
	@Autowired
	private DrinkRepository drinkRepository;

	public Order save(Order order) {
		return oRepository.save(order);
	}

	public List<Order> getAll() {
		return oRepository.findAll();
	}

	public List<Order> findByCustomer(String customer) {
		return oRepository.findByCustomer(customer);
	}

	public Order findById(Long id) {
		return oRepository.findById(id).orElse(null);
	}

	public Order update(Order order) {
		Optional<Order> orderOptional = oRepository.findById(order.getId());
		if(!orderOptional.isPresent()) {
			return null;
		}

		return oRepository.saveAndFlush(order);
	}
	
	public boolean changeState(Order order, OrderState state){
		if (state.compareTo(order.getState()) <= 0) {
			log.warn("状态不能从{}到{}", order.getState(), state);
			return false;
		}
		
		order.setState(state);
		Order newOrder = oRepository.saveAndFlush(order);
		log.info("更改后的订单{}", newOrder);
		return true;
	}

	public boolean delete(Long id) {
		try{
			oRepository.deleteById(id);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public Order saveOrder(NewOrderRequest o) {
		var drinks = new ArrayList<Drink>();
		
		for (Long drinkId : o.getDrinks()) {
			drinks.add(drinkRepository.findById(drinkId).orElse(null));
		}
		
		return oRepository.save(Order.builder().customer(o.getUser()).items(drinks).state(OrderState.INIT).build());
	}
	
	public Order cancle(Long id) {
		Optional<Order> orderOpt = oRepository.findById(id);
		if (orderOpt.isPresent()) {
			Order order = orderOpt.get();
			order.setState(OrderState.CANCEL);
			return oRepository.save(order);
		}
		return null;
	}
	
	public List<Order> find(String startDate, String endDate,String username) {
		
		return oRepository.findByCustomerAndAndCreateTimeBetween(username,LocalDateTime.parse(startDate + "T00:00"), LocalDateTime.parse(endDate+ "T00:00"));
	}
	
	public Order active(Long id) {
		Optional<Order> orderOpt = oRepository.findById(id);
		if (orderOpt.isPresent()) {
			Order order = orderOpt.get();
			order.setState(OrderState.INIT);
			return oRepository.save(order);
		}
		return null;
	}
}